<template>
  <el-card class="el-card--has-heading success">
    <div slot="header" class="v-card__headerInner">
      <p>优惠卷</p>
      <transition name="el-zoom-in-center">
        <div v-show="showTip">
          <p class="v-card__header-tip">{{showForm
            ? '先选择 [适用范围] 再选择 [适用对象]'
            : '优惠卷分为满减和满折扣两种类型'}}</p>
        </div>
      </transition>
      <el-button
        class="v-card__headerAction"
        type="text"
        @click="onClickCreate"
        v-auth:[$P.productOperation.discountCoupon.create]
      >{{showForm ? '返回列表' : '创建优惠卷'}}</el-button>
    </div>
    <transition name="scale-ani">
      <DiscountCouponForm
        :record="record"
        ref="form"
        key="DiscountCouponForm"
        @submit="handleSubmit"
        v-loading="formLoading"
        v-if="showForm"
      />
      <v-table
        v-else
        key="vtable"
        :dataSource="dataSource"
        :columns="filterColumn(columns,[$P.productOperation.discountCoupon.update,$P.productOperation.discountCoupon.delete])"
        :loading="loading"
        :total="total"
        v-bind="bindProps"
        v-on="bindListeners"
      >
        <template slot="toolbar">
          <el-form inline size="small" :model="query" ref="query" class="flex flex-wrap">
            <el-form-item prop="couponName">
              <el-input placeholder="请输入优惠卷名称" v-model.trim="query.couponName" />
            </el-form-item>

            <el-form-item prop="couponState">
              <el-select v-model="query.couponState" placeholder="请选择优惠券状态">
                <el-option
                  v-for="(it, i) in onlineStatus"
                  :key="i"
                  :label="it.label"
                  :value="+it.value === 1 ? 'online' : 'offline'"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="couponApplicableScope">
              <el-select v-model="query.couponApplicableScope" placeholder="请选择适用范围">
                <el-option
                  v-for="(it, i) in discountCouponCategory"
                  :key="i"
                  :label="it.label"
                  :value="it.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="couponDistributionMethod">
              <el-select v-model="query.couponDistributionMethod" placeholder="请选择发放方式">
                <el-option
                  v-for="(it, i) in discountCouponMethods"
                  :key="i"
                  :label="it.label"
                  :value="it.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="couponType">
              <el-select v-model="query.couponType" placeholder="请选择优惠卷类型">
                <el-option
                  v-for="(it, i) in discountCouponTypes"
                  :key="i"
                  :label="it.label"
                  :value="it.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="success" @click="handleSearch">查询</el-button>
              <el-button type="warning" @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </template>
      </v-table>
    </transition>
  </el-card>
</template>

<script>
import {
  getDiscountCouponList,
  createDiscountCoupon,
  updateDiscountCoupon,
  deleteDiscountCoupon,
  onlineDiscountCoupon,
  offlineDiscountCoupon,
  getDiscountCouponById,
  getFreshGoodsByIds,
  getFreshClassifyByIds,
  getMaintenanceGoodsByIds,
  getMaintenanceClassifyByIds
} from '@/api'

/* components
---------------------------------------------------------------- */
import DiscountCouponForm from './components/DiscountCouponForm'
import { Query, Emitter } from '@/mixins'

/* model
---------------------------------------------------------------- */
import {
  primaryKey,
  discountCouponTypes,
  discountCouponValidity,
  discountCouponMethods,
  discountCouponCategory
} from './model'

import { onlineStatusEnum } from '@/core/enum'

export default {
  componentName: 'DiscountCoupon',
  mixins: [Query('query'), Emitter],

  data () {
    return {
      discountCouponCategory,
      discountCouponTypes,
      discountCouponValidity,
      discountCouponMethods,
      showTip: false,
      total: 0,
      dataSource: [],
      loading: false,
      columns: [
        { prop: 'couponName', label: '名称' },
        {
          prop: 'couponApplicableScopeValue',
          label: '适用范围'
        },
        {
          prop: 'couponTypeValue',
          label: '优惠卷类型'
        },
        {
          prop: 'couponType',
          label: '优惠内容',
          formatter: (row) => {
            const text =
              row.couponType === discountCouponTypes[0].value
                ? `满 ${row['couponBaseAmount']} 减 ${row['couponReducedAmount']}`
                : `满 ${row['couponBaseAmount']} 打 ${row['couponDiscount']} 折`
            return <span class="striking">{text}</span>
          }
        },
        {
          prop: 'couponValidityTermTypeValue',
          label: '有效类型'
        },
        {
          prop: 'couponValidityTermType',
          label: '有效期',
          formatter: (row) => {
            const text =
              row.couponValidityTermType === discountCouponValidity[0].value
                ? `${row['couponValidityTermStart']} - ${row['couponValidityTermEnd']}`
                : `${row['couponValidityTerm']}天`
            return <span class="striking">{text}</span>
          }
        },
        {
          prop: 'couponStateValue',
          label: '状态',
          width: this.$V.cellSize.status,
          formatter: (row) => (
            <el-link
              type={
                row['couponState'].toLowerCase() !== 'online'
                  ? 'danger'
                  : 'success'
              }
              onClick={() =>
                this.toggleOnline(
                  row['couponState'].toLowerCase() !== 'online',
                  row
                )
              }
            >
              {row['couponStateValue']}
            </el-link>
          )
        },
        {
          prop: 'couponCreateTime',
          label: '创建时间',
          width: this.$V.cellSize.date,
          formatter: (row) => this.$formatTime(row['couponCreateTime'])
        },
        { prop: 'couponCreateUserName', label: '创建人' },
        {
          prop: 'couponUpdateTime',
          label: '修改时间',
          width: this.$V.cellSize.date,
          formatter: (row) => this.$formatTime(row['couponUpdateTime'])
        },
        { prop: 'couponUpdateUserName', label: '修改人' },
        {
          label: '操作',
          minWidth: this.$V.cellSize.action,

          formatter: this.getActionDecorator([
            {
              icon: 'el-icon-edit',
              action: this.onClickUpdate,
              auth: this.$P.productOperation.discountCoupon.update,
              type: 'primary'
            },
            {
              icon: 'el-icon-delete',
              action: this.onClickDelete,
              auth: this.$P.productOperation.discountCoupon.delete,
              type: 'danger'
            }
          ])
        }
      ],
      record: {},
      query: {
        couponDistributionMethod: ''
      },

      // -------- Form ----------
      showForm: false,
      formLoading: false,
      actionType: ''
      // -------- !Form ----------
    }
  },
  methods: {
    // Requests
    // ------------------------------------------
    getDiscountCouponList (fn) {
      return this.Catch(getDiscountCouponList, {
        onOk (res) {
          this.dataSource = res.data.data
          this.total = res.data.total
          if (
            this.dataSource.find(
              (row) =>
                row.couponValidityTermType === discountCouponValidity[0].value
            )
          ) {
            this.updateColumnByProp('couponValidityTermType', (col) => {
              col.width = '200px'
            })
          } else {
            this.updateColumnByProp('couponValidityTermType', (col) => {
              col.width = ''
            })
          }
        }
      })('loading', (fn || this.$noop)(this.query))
    },

    getDiscountCouponById (id, { onOk, onError }) {
      return this.Catch(getDiscountCouponById, {
        onOk,
        onError
      })('loading', id)
    },

    deleteDiscountCoupon (id, { onOk }) {
      return this.Catch(deleteDiscountCoupon, {
        onOk
      })(null, id)
    },

    createDiscountCoupon (data) {
      return this.Catch(createDiscountCoupon, {
        onOk () {
          this.$message.success(this.$t('createOk'))
          this.getDiscountCouponList()

          this.showForm = false
        }
      })('formLoading', data)
    },

    updateDiscountCoupon (id, data) {
      return this.Catch(updateDiscountCoupon, {
        onOk () {
          this.$message.success(this.$t('updateOk'))
          this.getDiscountCouponList()
          this.showForm = false
        }
      })('formLoading', id, data)
    },

    onlineDiscountCoupon (id) {
      return this.Catch(onlineDiscountCoupon, {
        onOk () {
          this.$message.success('上线成功')
          this.getDiscountCouponList()
        }
      })(null, id)
    },

    offlineDiscountCoupon (id) {
      return this.Catch(offlineDiscountCoupon, {
        onOk () {
          this.$message.success('下线成功')
          this.getDiscountCouponList()
        }
      })(null, id)
    },

    getFreshGoodsByIds (ids, { onOk, onError }) {
      return this.Catch(getFreshGoodsByIds, {
        onOk,
        onError
      })('loading', ids)
    },
    getFreshClassifyByIds (ids, { onOk, onError }) {
      return this.Catch(getFreshClassifyByIds, {
        onOk,
        onError
      })('loading', ids)
    },
    getMaintenanceGoodsByIds (ids, { onOk, onError }) {
      return this.Catch(getMaintenanceGoodsByIds, {
        onOk,
        onError
      })('loading', ids)
    },
    getMaintenanceClassifyByIds (ids, { onOk, onError }) {
      return this.Catch(getMaintenanceClassifyByIds, {
        onOk,
        onError
      })('loading', ids)
    },

    // Table
    // ------------------------------------------

    updateColumnByProp (prop, callback) {
      const col = this.columns.find((i) => i.prop === prop)
      if (col && typeof callback === 'function') {
        callback(col)
      }
    },

    toggleOnline (willOnline, row) {
      this.ConfirmToggleOnline({
        online: willOnline,
        onOk: () =>
          willOnline
            ? this.onlineDiscountCoupon(row[primaryKey])
            : this.offlineDiscountCoupon(row[primaryKey])
      })
    },

    onClickDelete (row) {
      this.ConfirmDelete({
        onOk: () =>
          this.deleteDiscountCoupon(row[primaryKey], {
            onOk () {
              this.$message.success(this.$t('deleteOk'))
              this.getDiscountCouponList()
            }
          })
      })
    },

    async onClickUpdate (row) {
      const openModal = (data) => {
        this.showForm = true
        this.record = data
      }

      this.getDiscountCouponById(row[primaryKey], {
        onOk ({ data }) {
          this.actionType = 'update'
          const {
            couponValidityTermStart,
            couponValidityTermEnd,
            couponValidityTermType,
            couponDistributionMethodList
          } = data

          // 处理日期范围回显
          if (couponValidityTermType === discountCouponValidity[0].value) {
            data._couponValidityTermRange = [
              couponValidityTermStart || '',
              couponValidityTermEnd || ''
            ]
          }

          // 处理发放方式
          if (
            couponDistributionMethodList &&
            couponDistributionMethodList.length
          ) {
            data._couponDistributionMethodList = couponDistributionMethodList.map(
              (it) => it.couponDistributionMethod
            )
          }

          // 处理两种购物满
          let target
          if (
            (target = couponDistributionMethodList.find(
              (it) =>
                it.couponDistributionMethod === discountCouponMethods[2].value
            ))
          ) {
            data._couponDistributionMethodBaseAmount_Refresh =
              target.couponDistributionMethodBaseAmount
          }
          if (
            (target = couponDistributionMethodList.find(
              (it) =>
                it.couponDistributionMethod === discountCouponMethods[3].value
            ))
          ) {
            data._couponDistributionMethodBaseAmount_Maintenance =
              target.couponDistributionMethodBaseAmount
          }

          // 处理tagbox回显
          if (
            data.couponApplicableResource &&
            data.couponApplicableResourceType
          ) {
            let request

            switch (data.couponApplicableResourceType) {
              case 'FRESH_GOODS':
                request = this.getFreshGoodsByIds
                break
              case 'FRESH_CLASSIFY':
                request = this.getFreshClassifyByIds
                break
              case 'MAINTENANCE_GOODS':
                request = this.getMaintenanceGoodsByIds
                break
              case 'MAINTENANCE_CLASSIFY':
                request = this.getMaintenanceClassifyByIds
                break
            }

            if (!request) {
              openModal(data)
            } else {
              request(data.couponApplicableResource, {
                onOk (res) {
                  openModal({
                    ...data,
                    _couponApplicableResource: res.data
                  })
                }
              })
            }
          } else {
            openModal(data)
          }
        }
      })
    },

    async onClickCreate () {
      this.actionType = 'create'
      this.record = {}
      this.showForm = !this.showForm
    },

    // Modal
    // ------------------------------------------
    handleSubmit () {
      this.$refs.form.submit((valid, values) => {
        if (valid) {
          if (this.actionType === 'create') {
            this.createDiscountCoupon(values)
          } else {
            this.updateDiscountCoupon(values[primaryKey], values)
          }
        }
      })
    }
  },
  computed: {
    onlineStatus () {
      return this.$mapEnumToSelect(onlineStatusEnum)
    }
  },
  components: { DiscountCouponForm },

  created () {
    this.getDiscountCouponList()

    this.inject(this.getDiscountCouponList)

    this.$on('picker.open', this.openPicker)

    this.$nextTick(() => (this.showTip = true))
  }
}
</script>
<style lang="scss" scoped>
.striking {
  // 颜色加重提醒用户
  color: #1b8038;
}
</style>
